﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Configuration;
using System.ServiceModel.Activation;
using ZX.DBModule;
using ZX.Common;
using ZX.BLL;

namespace UploadWcfService
{
    // 注意: 如果更改此处的类名 "UpLoadService"，也必须更新 Web.config 中对 "UpLoadService" 的引用。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class UpLoadService : IUpLoadService
    {

        private const int BufferLen = 4096;
        private static Dictionary<string, int> _uploadInfoDict = new Dictionary<string, int>();
        private static object _lockObj = new object();


       

        public void UploadFile(FileUploadMessage request)
        {
            string json = request.SavePath;
            iSun.Entity.ProductImage entity = ZX.Common.Globals.JSonToObject<iSun.Entity.ProductImage>(json);
            entity.AddTime = System.DateTime.Now;
            entity.AddUser = Guid.Empty;
            entity.DateLastModified = System.DateTime.Now;
            string savaPath = entity.FilePath;
            entity.FilePath = (entity.StepN == 0 ? "\\Upload\\Photo\\" : "\\Upload\\Photo1\\") + entity.FilePath + entity.fileName;
            string uploadFolder = entity.StepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
            iSun.Entity.ProductPhotoEnitty _entity = new iSun.Entity.ProductPhotoEnitty();
            ZX.BLL.Extend.BaseBussnies _bll = new ZX.BLL.Extend.BaseBussnies(_entity);
            string[] _str = savaPath.Split('\\')[0].Split('_');

            int vendor_id = _str.Length <= 1 ? 1 : (string.IsNullOrEmpty(_str[1]) ? 1 : Convert.ToInt32(_str[1]));
            IList<iSun.Entity.ProductPhotoEnitty> __list = _bll.GetEntitys<iSun.Entity.ProductPhotoEnitty>("SN='" + entity.SN.Split('_')[0] + "' and Vendor_id='" + vendor_id + "'");
            if (__list == null)
            {
                //iSun.Entity.ProductPhotoEnitty __entity = new iSun.Entity.ProductPhotoEnitty();
                _entity.ID = new Guid();
                _entity.SN = entity.SN.Split('_')[0];
                //string[] _str = savaPath.Split('\\')[0].Split('_');
                _entity.Vendor_id = vendor_id;
                _entity.ProductName = _entity.SN;
                //entity.UserName;
                _entity.AddTime = System.DateTime.Now;
                SaveProductData(_entity);
                entity.ProductID = _entity.ID;
            }
            else
            {
                entity.ProductID = __list[0].ID;
            }
            entity.SN = entity.SN.Split('_')[0];
            string dateString = DateTime.Now.ToShortDateString() + @"\";
            string fileName = request.FileName;
            Stream sourceStream = request.FileData;
            FileStream targetStream = null;

            if (!sourceStream.CanRead)
            {
                throw new Exception("数据流不可读!");
            }
            if (savaPath == null) savaPath = @"Photo\";
            if (!savaPath.EndsWith("\\")) savaPath += "\\";

            uploadFolder = uploadFolder + savaPath;
            uploadFolder = uploadFolder.ToLower().Replace("\\modifing", "");
            if (!Directory.Exists(uploadFolder))
            {
                Directory.CreateDirectory(uploadFolder);
            }
            //if(uploadFolder.Contains(""):
            string filePath = (uploadFolder + fileName);
             
            using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                entity.FilePath = entity.FilePath.ToLower().Replace("\\modifing", "");
                //read from the input stream in 4K chunks
                //and save to output stream
                const int bufferLen = BufferLen;
                byte[] buffer = new byte[bufferLen];
                int count = 0;

                //SetFileUploadInfo(savaPath, 0);
                while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                    if (entity.FileSize != 0)
                    {
                        if (entity.FileSize - (int)targetStream.Length > 100000)
                        {
                            //SaveProgress(savaPath + entity.fileName, entity.FileSize, (int)targetStream.Length, 0);
                            SetFileUploadInfo(entity.FilePath.ToLower(), (int)targetStream.Length);
                            //System.Threading.Thread.Sleep(50);
                        }
                    }

                }
                if (entity.FileSize != 0)
                {
                    SetFileUploadInfo(entity.FilePath.ToLower(), entity.FileSize);
                    //SaveProgress(savaPath+entity.fileName, entity.FileSize, entity.FileSize, 0);
                }
                targetStream.Close();
                sourceStream.Close();
                SaveFileData(entity);
                _uploadInfoDict.Remove(entity.FilePath);
            }


            #region 将上传的文件备份一份到服务器
            string __newPath = ConfigurationManager.AppSettings["backPath"]+entity.FilePath;
            if(!Directory.Exists( ZX.Common.FileHelper.GetFileDir(__newPath)))
            {
                Directory.CreateDirectory( ZX.Common.FileHelper.GetFileDir(__newPath));
            }
            System.IO.File.Copy(filePath, __newPath,true);
            #endregion 
        }

        public IList<iSun.Entity.ProductPhotoEnitty> GetProductsBySN(string SN)
        {
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            IList<iSun.Entity.ProductPhotoEnitty> list  = bll.GetEntitys<iSun.Entity.ProductPhotoEnitty>("SN='"+SN+"'");
            return list;
        }

        public FileUploadMessage GetProduct(DownloadRequest request)
        {
            FileUploadMessage data = new FileUploadMessage();

            System.IO.Stream sourceStream = new FileStream(ConfigurationManager.AppSettings["filePath"] + request.FileName, FileMode.Open);
     
            data.FileData = sourceStream;
            //sourceStream.Close();
            //sourceStream.Close();
            return data;
            //return file;
        }

        public void UploadProduct(string request)
        {
            IList<iSun.Entity.ProductPhotoEnitty> list = ZX.Common.Globals.JSonToObject<IList<iSun.Entity.ProductPhotoEnitty>>(request);
            iSun.Entity.ProductPhotoEnitty entity = new iSun.Entity.ProductPhotoEnitty();
            ZX.BLL.Extend.BaseBussnies _bll = new ZX.BLL.Extend.BaseBussnies(entity);

            IList<iSun.Entity.ProductPhotoEnitty> _list = _bll.GetEntitys<iSun.Entity.ProductPhotoEnitty>();
            foreach (iSun.Entity.ProductPhotoEnitty _entity in list)
            {
                if (_list==null || _list.Where(p => p.SN == _entity.SN && p.Vendor_id==_entity.Vendor_id).Count() == 0)
                {
                    SaveProductData(_entity);
                }
            }
        }

        public IList<string> GetFiles()
        {
            IList<string> list = new List<string>();
            string uploadFolder = ConfigurationManager.AppSettings["filePath"];
            DirectoryInfo dir = new DirectoryInfo(uploadFolder);
            FileInfo[] allFile = dir.GetFiles();
            uFile(uploadFolder, uploadFolder, list);
            return list;
        }


        public IList<string> GetSNFiles(string SN,bool isSourceFile)
        {
            return GetProductFiles(SN, isSourceFile ? 0 : 1);
            //IList<string> list = new List<string>();
            //string uploadFolder = (isSourceFile ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"]) + (SN == "root" ? "" : SN);
            //if (Directory.Exists(uploadFolder))
            //{
            //    DirectoryInfo dir = new DirectoryInfo(uploadFolder);
            //    FileInfo[] allFile = dir.GetFiles();
            //    uFile(uploadFolder, uploadFolder, list);
            //}
            //else
            //{
            //    ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            //    IList<iSun.Entity.ProductImage> _list = bll.GetEntitys<iSun.Entity.ProductImage>("ProductID ='"+SN+"'");
            //    foreach (var entity in _list)
            //    {
            //        list.Add(entity.FilePath);
            //    }
            //}
            //return list;
        }

        public IList<string>  GetProductFiles(string productID,int stepN)
        {
            IList<string> list = new List<string>();
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            IList<iSun.Entity.ProductImage> _list = bll.GetEntitys<iSun.Entity.ProductImage>("ProductID ='" + productID + "' and stepN="+stepN);
            
            foreach (var entity in _list)
            {
                list.Add(entity.FilePath);
            };
            return list;
    }

        public IList<string> GetProductImages(string productid)
        {
            IList<string> list = new List<string>();

            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            IList<iSun.Entity.ProductImage> _list = bll.GetEntitys<iSun.Entity.ProductImage>("ProductID ='" + productid.ToString() + "'");
            foreach (var entity in _list)
            {
                list.Add(entity.FilePath);
            }
            return list;
        }

        //public IList<string> GetSNFiles(string SN, bool isSourceFile)
        //{
        //    IList<string> list = new List<string>();
        //    string uploadFolder = (isSourceFile ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"]) + (SN == "root" ? "" : SN);
        //    if (Directory.Exists(uploadFolder))
        //    {
        //        DirectoryInfo dir = new DirectoryInfo(uploadFolder);
        //        FileInfo[] allFile = dir.GetFiles();

        //        uFile(uploadFolder, uploadFolder, list);
        //    }
        //    return list;
        //}
         
       

        void uFile(string path,string mainPath, IList<string> list)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
                list.Add(fi.FullName.Replace(mainPath, ""));
            }
            foreach (DirectoryInfo _dir in dir.GetDirectories())
            {
                uFile(_dir.FullName,mainPath,list);
            }
        }

        public void SaveFileData(iSun.Entity.ProductImage entity)
        {
            //ZX.DBModule.DataTableBaseEntity dtEntity = new DataTableBaseEntity();

            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
            // var o =  bll.GetEntityByCondition<iSun.Entity.ProductImage>(string.Format("FilePath='{0}'",entity.FilePath));
            bll.RunSqlCommand(string.Format("delete from gs_ProductImage where FilePath='{0}';", entity.FilePath));
            //if (o == null)
            //{
            bll.Insert();
            // }
            //    //else
            //    {
            //    //    entity.ID = o.ID;
            //     //   bll.Update();
            //    }
        }

        //public void SaveFileData(iSun.Entity.ProductImage entity)
        //{
        //    //ZX.DBModule.DataTableBaseEntity dtEntity = new DataTableBaseEntity();
        //    ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
        //    bll.Insert();
        //}
        
        public void SaveProductData(iSun.Entity.ProductPhotoEnitty entity)
        {
            //ZX.DBModule.DataTableBaseEntity dtEntity = new DataTableBaseEntity();
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
            bll.Insert();
        }

        public bool IsExistsProduct(string SN)
        {
            iSun.Entity.ProductPhotoEnitty entity = new iSun.Entity.ProductPhotoEnitty();
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
            entity = bll.GetEntityByCondition<iSun.Entity.ProductPhotoEnitty>("SN='" + SN + "'");
            return entity != null;
        }

        public iSun.Entity.ProductPhotoEnitty GetProduct(string productID)
        {
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            return bll.GetEntityById<iSun.Entity.ProductPhotoEnitty>(new Guid(productID));
        }
        
        public void DeleteProuct(string productID)
        {
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            bll.RunSqlCommand(string.Format("delete from gs_ProductImage where productID='{0}';delete from gs_Product where id='{0}';", productID));
            try
            {
                 iSun.Entity.ProductPhotoEnitty Entity = GetProduct(productID);
                 string SN = Entity.SN;
                string sourcePath = ConfigurationManager.AppSettings["filePath"];
                string tagetPath = ConfigurationManager.AppSettings["filePath1"];
                if (System.IO.Directory.Exists(sourcePath + SN + "_" + Entity.Vendor_id))
                {
                    //string sourcePath = ConfigurationManager.AppSettings["filePath"];
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(sourcePath + SN + "_" + Entity.Vendor_id);
                    dir.Delete(true);
                }
                //else
                //{
                //    //string sourcePath = ConfigurationManager.AppSettings["filePath"];
                //    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(sourcePath + SN);
                //    dir.Delete(true);
                //}
                if (System.IO.Directory.Exists(tagetPath + SN + "_" + Entity.Vendor_id))
                {
                    //string tagetPath = ConfigurationManager.AppSettings["filePath1"];
                    System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(tagetPath + SN + "_" + Entity.Vendor_id);
                    dir1.Delete(true);
                }
                //else
                //{
                //    //string tagetPath = ConfigurationManager.AppSettings["filePath1"];
                //    System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(tagetPath + SN);
                //    dir1.Delete(true);
                //}
            }
            catch (Exception e1)
            {
            }
        }

        public void DeleteProuctImages(string images)
        {
            string[] imagePath = images.Split(',');
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            foreach (string _image in imagePath)
            {
                string webPath = ConfigurationManager.AppSettings["filePath"].Replace("\\upload\\Photo","");
                webPath = webPath + _image;
                if (System.IO.File.Exists(webPath))
                {
                    try
                    {
                        System.IO.File.Delete(webPath);
                    }catch(Exception ex)
                    {

                    }
                }
                bll.RunSqlCommand(string.Format("delete from gs_ProductImage where FilePath='{0}';", _image));
            }
        }

        public void SetFlag(string SN, string Flag)
        {
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            bll.RunSqlCommand(string.Format("update gs_Product set {0}='1' from gs_ProductImage where SN='{1}';",Flag,SN));
        }

        //public int GetUploadFileInfo(string filePath)
        //{
        //    ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
        //    var entity = bll.GetEntityByCondition<iSun.Entity.GsProgress>(string.Format(" FilePath = '{0}'", "\\Upload\\Photo\\" + filePath));
        //    return entity == null ? 0 : entity.Progress;
        //}

        public int GetUploadFileInfo(string filePath)
        {
            string _filePath = filePath.ToLower();// filePath.ToLower().Replace("\\upload\\photo1\\", "").Replace("\\upload\\photo\\", "");
            if (_uploadInfoDict.ContainsKey(_filePath))
                return _uploadInfoDict[_filePath];
            else
                return 0;
        }

        private void SetFileUploadInfo(string id, int savedFileCount)
        {
            lock (_lockObj)
            {

                if (_uploadInfoDict.ContainsKey(id))
                    _uploadInfoDict[id] = savedFileCount;
                else
                    try
                    {
                        _uploadInfoDict.Add(id, savedFileCount);
                    }
                    catch(Exception e) { }
            }
        }



        private void SaveProgress(string filePath, int filesize, int progress, int flag)
        {
            iSun.Entity.GsProgress entity = new iSun.Entity.GsProgress();
            ZX.BLL.Extend.BaseBussnies _bll = new ZX.BLL.Extend.BaseBussnies(entity);
            if (progress == filesize)
            {

                //_bll.RunSqlCommand(string.Format("delete from gs_Progress where FilePath='{0}';", entity.FilePath));
                return;
            }
            entity = _bll.GetEntityByCondition<iSun.Entity.GsProgress>(string.Format(" FilePath='{0}'", filePath));
            //_bll.RunSqlCommand(string.Format("delete from gs_Progress where FilePath='{0}'", filePath));
            if (entity == null)
            {
                entity = new iSun.Entity.GsProgress();
                entity.ID = new Guid();
                entity.FilePath = filePath;
                entity.FileSize = filesize;
                entity.Progress = progress;
                entity.Flag = flag;
                _bll.entity = entity;
                _bll.Insert();
            }
            else
            {
                _bll.RunSqlCommand(string.Format("update  gs_Progress set Progress={0} where FilePath='{1}'", progress, filePath));
            }
        }
    }
}
